package org.dubbo.live.common.interfaces.service.Impl;

import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dubbo.live.common.interfaces.service.ImService;
import org.dubbo.live.common.interfaces.vo.resp.ImConfigVO;
import org.qiyu.live.im.constants.AppIdEnum;
import org.qiyu.live.im.interfaces.ImTokenRpc;
import org.qiyu.live.web.starter.context.QiyuRequestContext;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Description: //todo
 * @Author: 张广焱
 * @Date: 2024-06-12 下午8:40
 */
@Service
public class ImServiceImpl implements ImService {
    @DubboReference
    private ImTokenRpc imTokenRpc;
    @Resource
    private DiscoveryClient discoveryClient;

    @Override
    public ImConfigVO getImConfig() {
        String token = imTokenRpc.createImLoginToken(QiyuRequestContext.getUserId(), AppIdEnum.QIYU_LIVE_BIZ.getCode());
        ImConfigVO imConfigVO = new ImConfigVO();
        imConfigVO.setToken(token);
        this.getImServerAddress(imConfigVO);
        return null;
    }

    private void getImServerAddress(ImConfigVO imConfigVO) {
        List<ServiceInstance> instances = discoveryClient.getInstances("qiyu-live-im-core-server");
        // 随机选择一个实例 打乱顺序
        Collections.shuffle(instances);
        ServiceInstance aimInstance = instances.get(0);
        imConfigVO.setWsImServerAddress(aimInstance.getHost() + ":8086");
        imConfigVO.setTcpImServerAddress(aimInstance.getHost() + ":8085");
    }
}
